#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
build command implementation
"""

import os
import logging
import sys
from trustimage.core.parser import TrustedImageParser
from trustimage.core.builder import ImageBuilder, BuildError

logger = logging.getLogger(__name__)

def setup_parser(parser):
    """
    Set command line arguments
    
    Args:
        parser: Argument parser
    """
    parser.add_argument('-f', '--file', default='TrustedImageFile', help='Specify config file path')
    parser.add_argument('-o', '--output-dir', default='.', help='Output directory')

def execute(args):
    """
    Execute build command
    
    Args:
        args: Command line arguments
    
    Returns:
        int: Return code, 0 for success, non-0 for failure
    """
    try:
        file_path = args.file
        output_dir = args.output_dir
        
        if not os.path.exists(file_path):
            logger.error(f"Config file does not exist: {file_path}")
            return 1
        
        if not os.path.isdir(output_dir):
            logger.info(f"Creating output directory: {output_dir}")
            os.makedirs(output_dir, exist_ok=True)
        
        logger.info(f"Start building image from {file_path}")
        
        # Parse config file
        parser = TrustedImageParser(file_path)
        
        # Build image
        builder = ImageBuilder(parser, output_dir)
        
        try:
            # Prepare build environment
            builder.prepare()
            
            # Execute build
            output_path = builder.build()
            
            logger.info(f"Image built successfully: {output_path}")
            return 0
        finally:
            # Clean up temporary files
            builder.cleanup()
    
    except BuildError as e:
        logger.error(f"Build failed: {e}")
        return 1
    except Exception as e:
        logger.exception(f"Unexpected error occurred: {e}")
        return 1 